package com.tcm.smarthealth.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

@Configuration
public class CorsConfig {

    @Value("${app.frontend-url:http://localhost:5173}")
    private String frontendUrl;

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                        .allowedOriginPatterns(resolveAllowedOriginPatterns())
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
                        .allowedHeaders("*")
                        .allowCredentials(true)
                        .maxAge(3600);
            }
        };
    }

    private String[] resolveAllowedOriginPatterns() {
        Set<String> origins = new LinkedHashSet<>();
        origins.addAll(Arrays.asList(
                "http://localhost:5173",
                "http://127.0.0.1:5173",
                "http://[::1]:5173",
                "http://0.0.0.0:5173",
                "http://10.*.*.*:5173",
                "http://172.16.*.*:5173",
                "http://172.17.*.*:5173",
                "http://172.18.*.*:5173",
                "http://172.19.*.*:5173",
                "http://172.20.*.*:5173",
                "http://172.21.*.*:5173",
                "http://172.22.*.*:5173",
                "http://172.23.*.*:5173",
                "http://172.24.*.*:5173",
                "http://172.25.*.*:5173",
                "http://172.26.*.*:5173",
                "http://172.27.*.*:5173",
                "http://172.28.*.*:5173",
                "http://172.29.*.*:5173",
                "http://172.30.*.*:5173",
                "http://172.31.*.*:5173",
                "http://192.168.*.*:5173"
        ));

        Arrays.stream(frontendUrl.split(","))
                .map(String::trim)
                .filter(StringUtils::hasText)
                .forEach(origins::add);

        return origins.toArray(new String[0]);
    }
}

